import { Component } from '@angular/core';

import { AlertController,Events,NavController } from 'ionic-angular';

import { SignupPage } from '../signup/signup';
import { TabsPage } from '../tabs/tabs';
import { User } from '../../providers/user';
import { AppData } from '../../providers/app-data';

@Component({
  templateUrl: 'build/pages/login/login.html'
})
export class LoginPage {
  login: {account?: string, password?: string} = {};
  submitted = false;

  constructor(public events: Events,public navCtrl: NavController,public alertCtrl: AlertController, public appData: AppData) {
    this.listenToLoginEvents();
  }

  listenToLoginEvents() {
    this.events.subscribe('login:success', () => {
      console.log('login:success');
      this.navCtrl.push(TabsPage);
    });
    this.events.subscribe('login:disabled', () => {
      console.log('login:disabled');
      let alert = this.alertCtrl.create({
        title: '帐号已被禁用！',
        buttons: [{
          text: 'OK',
          handler: () => {
            // close the sliding item
          }
        }]
      });
      // now present the alert on top of all other content
      alert.present();
    });
    this.events.subscribe('login:fail', () => {
      console.log('login:fail');
      // create an alert instance
      let alert = this.alertCtrl.create({
        title: '帐号或密码错误，请重新输入！',
        buttons: [{
          text: 'OK',
          handler: () => {
            // close the sliding item
          }
        }]
      });
      // now present the alert on top of all other content
      alert.present();
    });
    this.events.subscribe('login:notExist', () => {
      console.log('login:notExist2');
      let alert = this.alertCtrl.create({
        title: '帐号不存在，请确认！',
        buttons: [{
          text: 'OK',
          handler: () => {
            // close the sliding item

          }
        }]
      });
      // now present the alert on top of all other content
      alert.present();
    });
  }

  onLogin(form) {
    this.submitted = true;

    if (form.valid) {
      let user = new User();
      user.account = this.login.account;
      user.password = this.login.password;
      let result = this.appData.login(user);
      // console.log("result:"+result);
      // this.navCtrl.push(TabsPage);
    }
  }

  onSignup() {
    this.navCtrl.push(SignupPage);
  }
}
